package
{
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.SecurityErrorEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.utils.ByteArray;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;

	import Util.BitmapUtil;
	import Util.png2atfUtil;

	[SWF(width=500, height=395)]
	public class ATFTool extends Sprite
	{
		private var ui : UIPanel;


		private var sourceDir : String; //源
		private var exportDir : String; //目标
		private var platform : String; //平台
		private var compress : Boolean; //是否压缩
		private var mips : Boolean; //是否启用
		private var quality : int; //质量
		private var to_square : Boolean; //是否转换为正方形

		private var exportFiles : Vector.<File>;

		private var localMgr : LocalShareManager;

		private var atfXml : XML = <root><file id=""></file></root>;

		public function ATFTool()
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;

			ui = new UIPanel();
			ui.addEventListener("Export", onExport);
			ui.addEventListener("com", onAdd);
			ui.addEventListener("xml", onXmlChange);
			addChild(ui);
			localMgr = LocalShareManager.getInstance();

		}

		private function onAdd(evt : Event) : void
		{
			onXmlChange(null);
		}

		private function onXmlChange(evt : Event) : void
		{
			if (localMgr.get(ui.exportDir + "xml") != null)
			{
				var bytes : ByteArray = localMgr.get(ui.exportDir + "xml");
				var newBytes : ByteArray = new ByteArray();
				newBytes.writeBytes(bytes, 0, bytes.length);
				newBytes.position = 0;
				newBytes.uncompress();
				atfXml = new XML(newBytes);
			}
		}

		/**
		 * 点击了导出按钮
		 */
		private function onExport(e : Event) : void
		{
			ui.exportBtnEnabled = false;

			sourceDir = ui.sourceDir;
			exportDir = ui.exportDir;
			platform = ui.platform;
			compress = ui.compress;
			mips = ui.mips;
			quality = ui.quality;
			to_square = ui.to_square;

			exportFiles = new Vector.<File>();
			ergodicDirectory(new File(sourceDir));

			ui.clearLogs();
			ui.log("开始导出ATF...\n");
			ui.log("总共选择了" + exportFiles.length + "个文件.\n");

			if (exportFiles.length == 0)
			{
				ui.log("导出完毕.\n");
				ui.exportBtnEnabled = true;
			}
			else
			{
				setTimeout(function() : void
					{
						startExport(exportFiles.pop());
					}, 600);
			}
		}

		/**
		 * 遍历文件夹
		 * */
		private function ergodicDirectory(file : File) : void
		{
			var array : Array = file.getDirectoryListing();
			var f : File;
			var length : int = array.length;

			for (var i : int = 0; i < length; i++)
			{
				f = array[i];

				if (f.isDirectory && ui.converChilds)
				{
					createDir(f);
					ergodicDirectory(f);
				}
				else
				{
					if (f.extension != "png" && f.extension != "jpg")
					{
						copyFile(f);
					}
					else
					{
						exportFiles.push(f);
					}
				}
			}
		}

		/**创建文件夹*/
		private function createDir(file : File) : void
		{
			var path : String = file.nativePath.replace(sourceDir, exportDir);
			var f : File = new File(path);

			if (!f.exists)
			{
				f.createDirectory();
			}
		}

		/**复制文件*/
		private function copyFile(file : File) : void
		{
			var path : String = file.nativePath.replace(sourceDir, exportDir);
			var f : File = new File(path);
			f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onScurtyError);
			file.copyTo(f, true);

			function onScurtyError(evt : Event) : void
			{
				trace("错误：", f.nativePath)
			}
		}

		private var sourceFile : String;
		private var exportFile : String;
		private var reImageBytes : ByteArray;
		private var reFile : File;
		private var totalTime : int = 0;

		/**
		 * 开始输出
		 * */
		private function startExport(file : File) : void
		{
			var time : int = getTimer();

			if (totalTime == 0)
				totalTime = time;
			ui.log(file.name + "开始导出...剩余:" + exportFiles.length + "个文件...\n");

			var fs : FileStream = new FileStream();
			fs.open(file, FileMode.READ);
			var bytes : ByteArray = new ByteArray();
			fs.readBytes(bytes);
			fs.close();

			var md5 : String = MD5.hash(bytes.toString());

			var xmlLis : XMLList = atfXml.file.(@id == file.nativePath)

			sourceFile = file.nativePath;
			exportFile = sourceFile.replace(sourceDir, exportDir);
			exportFile = exportFile.replace("." + file.extension, ".atf");

			if (xmlLis.length() == 0)
			{
				atfXml.appendChild(<file id={file.nativePath} md5={md5}/>);
			}
			else if (xmlLis.@md5 == md5)
			{
				var tmpFile : File = new File(exportFile);

				if (tmpFile.exists)
				{
					exportComplement();
					return;
				}
			}
			else
			{
				xmlLis.@md5 = md5;
			}

			converCallBack(bytes, file);

			function converCallBack(b : ByteArray, f : File) : void
			{
				reImageBytes = b;
				reFile = f;
				png2atfUtil.converAtf(sourceDir, sourceFile, exportFile, platform, compress, mips, quality, converAtfCallBack, logCallBack);

				function converAtfCallBack() : void
				{
					//还原图片
					if (reImageBytes)
					{
						var fs : FileStream = new FileStream();
						fs.open(reFile, FileMode.WRITE);
						fs.writeBytes(reImageBytes);
						fs.close();
					}

					exportComplement();
				}
			}

			function logCallBack(text : String) : void
			{
				ui.log(text);
			}

			function exportComplement() : void
			{
				if (exportFiles.length > 0)
				{
					startExport(exportFiles.pop());
				}
				else
				{
					ui.log("导出完毕.\n");
					ui.log("耗时:" + ((getTimer() - totalTime) / 1000) + "秒");
					ui.exportBtnEnabled = true;
					var xmlBytes : ByteArray = new ByteArray();
					xmlBytes.writeUTFBytes(atfXml.toXMLString());
					xmlBytes.compress();
					localMgr.save(ui.exportDir + "xml", xmlBytes);
				}
			}
		}
	}
}